package com.jiyinit.web.core.mobile.controller;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.core.framework.base.util.JsonEntityTransform;
import com.jiyinit.core.framework.base.util.LogUtil;
import com.jiyinit.core.framework.base.util.MD5Util;
import com.jiyinit.web.core.business.dto.UserRequest;
import com.jiyinit.web.core.business.entity.TabCoreOrgEntity;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.business.service.OrgServiceImpl;
import com.jiyinit.web.core.business.service.UserRoleServiceImpl;
import com.jiyinit.web.core.business.service.UserServiceImpl;
import com.jiyinit.web.core.business.vo.ContactsVo;
import com.jiyinit.web.core.business.vo.OrgTreeVo;
import com.jiyinit.web.core.business.vo.UserRoleVo;
import com.jiyinit.web.core.common.logic.ParamCheckLogic;
import com.jiyinit.web.core.common.logic.ValidateResult;
import com.jiyinit.web.core.common.util.GlobalsUtils;
import com.jiyinit.web.core.common.util.UserUtil;
import com.jiyinit.web.core.common.vo.CurrentUserVo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.*;

/**
 * 用户管理
 *
 * @author zhaolaiwei
 * @version 1.0
 * @date 2017/4/13 9:01
 * @since 1.0
 */
@Controller
@RequestMapping("/mobile/muser")
public class MuserController {

    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MuserController.class);

    @Resource(name = "core.paramCheckLogic")
    private ParamCheckLogic paramCheckLogic;

    @Resource(name = "core.userServiceImpl")
    private UserServiceImpl userService;

    @Resource(name = "core.orgServiceImpl")
    private OrgServiceImpl orgService;

    @Resource(name = "core.userRoleServiceImpl")
    private UserRoleServiceImpl userRoleService;

    /**
     * 跳转到查询用户信息页面
     *
     * @param request
     * @return
     */
    @RequestMapping("/toFindUserList")
    public String toFindUserList(HttpServletRequest request) {
        return "/user/userList";
    }

    /**
     * 按条件查询用户信息
     *
     * @param request
     * @param userRequest
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/findByPage")
    public PagingResult findByPage(HttpServletRequest request, UserRequest userRequest) {
        userRequest.setLimit(10);
        PagingResult pagingResult = userService.getUserInfoListByCondiction(userRequest);
        LogUtil.info(LOGGER, "getTotalRecords:{},getTotalPages:{},getRows:{}", pagingResult.getTotalRecords(), pagingResult.getTotalPages(),pagingResult.getRows());
        return pagingResult;
    }

    /**
     * 跳到新增页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/add")
    public String add(HttpServletRequest request) {
        return "/user/add";
    }

    /**
     * 新增用户
     *
     * @param request
     * @param userRequest
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/save")
    public ResponseEntity<ResponseDto> save(HttpServletRequest request, UserRequest userRequest) {
        // 校验参数
        ValidateResult<UserRequest> validateResult = paramCheckLogic.checkParamValidate(userRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }
        TabCoreUserEntity coreUser = new TabCoreUserEntity();
        BeanUtils.copyProperties(userRequest, coreUser);
        String password = MD5Util.MD5Encode(userRequest.getPassword());
        coreUser.setPassword(password);
        coreUser.setCreateTime(new Date());
        coreUser.setCreateId(UserUtil.getCurrentUser().getUserId());
        coreUser.setLastModifyTime(new Date());
        coreUser.setLastModifyId(UserUtil.getCurrentUser().getUserId());
        coreUser.setUserStatus(new Integer(1));
        coreUser.setIsDelete(new Integer(0));

        int num = userService.insert(coreUser,userRequest.getRoleId());
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }

    /**
     * 跳到修改页面
     * @param request
     * @return
     */
    @RequestMapping(value = "/edit")
    public String edit(Model model,HttpServletRequest request,Integer userId) {
        LogUtil.info(LOGGER, "userId:{}", userId);
        TabCoreUserEntity coreUser = userService.getUserInfoByUserId(userId);
        TabCoreOrgEntity coreOrg = orgService.selectById(coreUser.getOrgId());
        UserRoleVo userRoleVo = userRoleService.selectUserRoleVoByUserId(coreUser.getUserId());
        model.addAttribute("user",coreUser);
        model.addAttribute("org",coreOrg);
        model.addAttribute("userRole",userRoleVo);
        return "/user/edit";
    }

    /**
     * 修改用户信息
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/modify")
    public ResponseEntity<ResponseDto> modify(HttpServletRequest request, UserRequest userRequest) {
        // 校验参数
        ValidateResult<UserRequest> validateResult = paramCheckLogic.checkParamValidate(userRequest);
        if (!validateResult.isSuccess()) {
            return new ResponseEntity<>(validateResult.getDto(), HttpStatus.OK);
        }
        TabCoreUserEntity coreUser = userService.getUserInfoByUserId(userRequest.getUserId());
        BeanUtils.copyProperties(userRequest, coreUser);

        CurrentUserVo currentUser = UserUtil.getCurrentUser();
        coreUser.setLastModifyId(currentUser.getUserId());
        coreUser.setLastModifyTime(new Date());

        int num = userService.updateUserInfoById(coreUser,userRequest.getRoleId());
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }

    /**
     * 删除用户信息
     * @param request
     * @param userIds
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/delete")
    public ResponseEntity<ResponseDto> delete(HttpServletRequest request,Integer[] userIds) {
        LogUtil.info(LOGGER, "userIds:{}", userIds);
        int num = userService.deleteUserLogicByIds(userIds);
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }

    /**
     * 检查用户登录名是否重否
     * @param request
     * @param loginName
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/check")
    public ResponseEntity<ResponseDto> check(HttpServletRequest request,String loginName) {
        LogUtil.info(LOGGER, "loginName:{}", loginName);
        TabCoreUserEntity coreUser = userService.getUserInfoByLoginName(loginName);
        if(coreUser == null){
            return new ResponseEntity<>(ResponseDto.responseOK(""), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail(""), HttpStatus.OK);
    }

    /**
     * 跳转到密码修改界面
     * @param request
     * @return
     */
    @RequestMapping(value = "/toModifyPassword")
    public String toModifyPassword(Model model,HttpServletRequest request,Integer userId) {
        TabCoreUserEntity coreUser = userService.getUserInfoByUserId(userId);
        model.addAttribute("user",coreUser);
        return "/user/modifyPassword";
    }


    /**
     * 修改密码
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/mmodifyPassword")
    public ResponseEntity<ResponseDto> delete(HttpServletRequest request) {
    	UserRequest userRequest = this.getJsonToTaskRequest(request);
        //判断密码是否一致
        if("".equals(userRequest.getPassword())){
            return new ResponseEntity<>(ResponseDto.responseFail("新密码不能为空"), HttpStatus.OK);
        }

        TabCoreUserEntity coreUser = userService.getUserInfoByUserId(userRequest.getUserId());
        String password = MD5Util.MD5Encode(userRequest.getPassword());
        String oldPassword = MD5Util.MD5Encode(userRequest.getOldPassword());
        if(!oldPassword.equals(coreUser.getPassword())){
            return new ResponseEntity<>(ResponseDto.responseFail("旧密码输入错误"),HttpStatus.OK);
        }

        if(!userRequest.getConfirmPassword().equals(userRequest.getPassword())){
            return new ResponseEntity<>(ResponseDto.responseFail("两次密码不一致"), HttpStatus.OK);
        }

        String defaultPwd=GlobalsUtils.getValue("DEFAULT_PWD");
        if(!Check.isNullStr(password)&&password.equals(defaultPwd))
        {
            return new ResponseEntity<>(ResponseDto.responseFail("新密码不能设置为初始密码"), HttpStatus.OK);
        }

        coreUser.setPassword(password);
//        CurrentUserVo currentUser = UserUtil.getCurrentUser();
        coreUser.setLastModifyId(userRequest.getLastModifyId());
        coreUser.setLastModifyTime(new Date());
        int num = userService.updateUserInfoById(coreUser,userRequest.getRoleId());
        if (num > 0) {
            return new ResponseEntity<>(ResponseDto.responseOK("success"), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("failed"), HttpStatus.OK);
    }

    /**
     * 
         * 按机构查询用户
         * @author wuyuefeng
         * @create 2017年4月27日 下午2:09:18
         * @param 
         * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/mfindUsersByOrId")
    public ResponseEntity<ResponseDto> findUsersByOrId(HttpServletRequest request) {
    	
    	UserRequest userRequest = this.getJsonToTaskRequest(request);
        LogUtil.info(LOGGER, "orgId:{}", userRequest.getOrgId());
        userRequest.setLimit(10);
        PagingResult pagingResult = userService.findUsersByOrId(userRequest);
        LogUtil.info(LOGGER, "getTotalRecords:{},getTotalPages:{},getRows:{}", pagingResult.getTotalRecords(), pagingResult.getTotalPages(),pagingResult.getRows());
        
        if(pagingResult.getTotalRecords()>0)
        	return new ResponseEntity<>(ResponseDto.responseOK(pagingResult), HttpStatus.OK);
        return new ResponseEntity<>(ResponseDto.responseFail("filed"), HttpStatus.OK);
    }
    
    private UserRequest getJsonToTaskRequest(HttpServletRequest request){
    	String logJson = request.getParameter("request_json");
    	LogUtil.info(LOGGER, "logJson:{}", logJson);
    	UserRequest userRequest = (UserRequest)JsonEntityTransform.json2Object(logJson, UserRequest.class);
    	return userRequest;
    }

    @ResponseBody
    @RequestMapping(value = "/findContacts")
    public ResponseEntity<ResponseDto>  findContacts(HttpServletRequest request) {
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        UserRequest userRequest = (UserRequest)JsonEntityTransform.json2Object(logJson, UserRequest.class);
        OrgTreeVo node =  userService.findContacts(userRequest);
        if(node != null)
            return new ResponseEntity<>(ResponseDto.responseOK(node), HttpStatus.OK);
        return new ResponseEntity<>(ResponseDto.responseFail("filed"), HttpStatus.OK);
    }
    @ResponseBody
    @RequestMapping(value = "/findContactsAndroid")
    public ResponseEntity<ResponseDto>  findContactsAndroid(HttpServletRequest request) {
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        UserRequest userRequest = (UserRequest)JsonEntityTransform.json2Object(logJson, UserRequest.class);
        //根据当前登录者的orgId，查询出最高的orgId
        Integer parentId = orgService.getTopParentOrgId(userRequest.getOrgId());
        List<TabCoreOrgEntity> orgList = orgService.getChildOrgById(parentId);
        Collections.sort(orgList, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                TabCoreOrgEntity u1 = (TabCoreOrgEntity) o1;
                TabCoreOrgEntity u2 = (TabCoreOrgEntity) o2;
                int i = u1.getOrgLevel().compareTo(u2.getOrgLevel());
                if(i == 0) {
                    int j  = u1.getPInOrder().compareTo(u2.getPInOrder());
                    if (j == 0) {
                        return u1.getInOrder().compareTo(u2.getInOrder());
                    }
                    return j;
                }
                return i;
            }
        });
        List<ContactsVo> userList =  userService.findContactsAndroid(userRequest);
        HashMap<String,Object> result = new HashMap<>();
        result.put("org",orgList);
        result.put("user",userList);

        //查询兼职用户信息，用于解决同一用户属于多个部门的问题
        if(orgList!=null&&orgList.size()>0)
        {
            List<ContactsVo> partTimeUserInfo=userService.getPartTimeUserInfo(orgList);
            userList.addAll(partTimeUserInfo);
        }

        if(orgList != null)
            return new ResponseEntity<>(ResponseDto.responseOK(result), HttpStatus.OK);
        return new ResponseEntity<>(ResponseDto.responseFail("filed"), HttpStatus.OK);
    }

    /**
     * 添加好友时，查询用户的 (根据用户姓名，手机号)
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "queryUsers")
    public ResponseEntity<ResponseDto> queryUsers(HttpServletRequest request){
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        UserRequest userRequest = (UserRequest)JsonEntityTransform.json2Object(logJson, UserRequest.class);
        List<ContactsVo> node =  userService.queryUsers(userRequest.getParam());
        if(node != null){
            return new ResponseEntity<>(ResponseDto.responseOK(node), HttpStatus.OK);
        }

        return new ResponseEntity<>(ResponseDto.responseFail("filed"), HttpStatus.OK);
    }
    /**
     * 联系人列表页面的 搜索
     */
    @ResponseBody
    @RequestMapping("findUsers")
    public ResponseEntity<ResponseDto> findUsers(HttpServletRequest request){
        LogUtil.info(LOGGER, "接口:{}", "/mobile/muser/findUsers");
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        UserRequest userRequest = (UserRequest) JsonEntityTransform.json2Object(logJson, UserRequest.class);
        List<TabCoreUserEntity> users = null;
//        if(userRequest.getType() == null ){
//            return new ResponseEntity<>(ResponseDto.responseFail("type不能为空"), HttpStatus.OK);
//        }F
        List<ContactsVo> LuserLst = null;
        List<ContactsVo> HuserLst = null;
        List<ContactsVo> result = new ArrayList<>();

        //搜索联系人
        Integer parentId = orgService.getTopParentOrgId(userRequest.getOrgId());
        List<TabCoreOrgEntity> orgList = orgService.getChildOrgById(parentId);
        result = userService.findUsersByCon(orgList, userRequest.getUserName());
        for(int i=0;i<result.size();i++){
            TabCoreOrgEntity tabCoreOrgEntity =orgService.selectById(result.get(i).getParentId());//查询公司名称
            result.get(i).setCompanyName(tabCoreOrgEntity.getOrgName());
        }

        List<Integer> exitsIdList=new ArrayList<Integer>();
        for(ContactsVo item:result)
        {
            if(!exitsIdList.contains(item.getUserId()))
            {
                exitsIdList.add(item.getUserId());
            }
        }

        HuserLst = userService.findFriends(userRequest.getUserId(), userRequest.getUserName());
        if(HuserLst!=null)
        {
            for(ContactsVo item:HuserLst)
            {
                if(!exitsIdList.contains(item.getUserId()))
                {
                    result.add(item);
                }
            }
        }
        LogUtil.info(LOGGER, "接口:/mobile/muser/findUsers,返回结果{}", JsonEntityTransform.object2Json(result));
        return new ResponseEntity<ResponseDto>(ResponseDto.responseOK(result),HttpStatus.OK);
    }

    /**
     * 查询用户信息
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/queryUserById")
    public ResponseEntity<ResponseDto> queryUserById(HttpServletRequest request){
        String logJson = request.getParameter("request_json");
        LogUtil.info(LOGGER, "logJson:{}", logJson);
        UserRequest userRequest = (UserRequest)JsonEntityTransform.json2Object(logJson, UserRequest.class);
        TabCoreUserEntity user = userService.getUserInfoByUserId(userRequest.getToUserId());
        if(user != null){
            return new ResponseEntity<>(ResponseDto.responseOK(user), HttpStatus.OK);
        }
        return new ResponseEntity<>(ResponseDto.responseFail("未查询到该用户的信息"), HttpStatus.OK);
    }
}
